package com.looeyWei;


import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;

public class MyFrame extends JFrame {

    DefaultListModel<String> listModel = new DefaultListModel<>();

    // 创建列表框
    JList<String> jList = new JList<>();

    public MyFrame(String title) {
        super(title);

        // 添加面板
        JPanel root = new JPanel();
        root.setLayout(new BorderLayout());
        this.setContentPane(root);

        MyControl c = new MyControl();
        root.add(c, BorderLayout.CENTER);

    }

    /**
     * 右键处理事件
     * @param e
     */
    private void listboxRightClicked(MouseEvent e) {

        int index = locationToIndex(jList, e.getPoint());
        System.out.println("右键点击" + index);

        if(index >= 0){
            jList.setSelectedIndex(index);
            // 弹出菜单
            JPopupMenu menu = new JPopupMenu();
            menu.add(new JMenuItem("测试"));
            menu.show(e.getComponent(), e.getX(), e.getY());
        }else{
            jList.clearSelection();
        }
    }

    /**
     * 更精确的计算，鼠标点击再哪一项
     * @param listBox
     * @param loction
     * @return
     */
    public static int locationToIndex(JList listBox, Point loction){
        int index = listBox.locationToIndex(loction);
        if(index < 0) return -1;

        // 进一步确认
        Rectangle bounds = listBox.getCellBounds(index, index);
        if(bounds.contains(loction))
            return index;
        return -1;
    }

    private void listboxClicked(MouseEvent e) {

        int index = jList.locationToIndex(e.getPoint());
        System.out.println("点击了" + index);

        // 进一步确认
        Rectangle bounds = jList.getCellBounds(index, index);
        if(!bounds.contains(e.getPoint())){
            System.out.println("点中了空白位置");
            jList.clearSelection();
            return;
        }
        // 单选
//        jList.setSelectedIndex(index);

        // 多选
       if(jList.isSelectedIndex(index)){
            jList.removeSelectionInterval(index, index);
        }else{
            jList.addSelectionInterval(index, index);
        }
    }

    public void exec(){
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(800, 600);
        this.setLocationRelativeTo(null);

        this.setVisible(true);
    }

}